class TestSuitesController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @title1 = 'Test suites'
    @url1 = '/test_suites/'
    @test_suite_pages, @test_suites = paginate :test_suites, :per_page => 10
  end

  def show
    @test_suite = TestSuite.find(params[:id])
    @title1 = 'Test suites'
    @url1 = '/test_suites/'
    @title2 = @test_suite.name
    @url2 = "/test_suites/show/#{params[:id]}"
  end

  def new
    @test_suite = TestSuite.new
    @build_types = BuildType.find_all
    @test_types = TestType.find_all
    @title1 = 'Test suites'
    @url1 = '/test_suites/'
    @title2 = 'New'
    @url2 = "/test_suites/new"
  end

  def create
    @test_suite = TestSuite.new(params[:test_suite])
    params[:builds].each { |k,v|
      @test_suite.build_types << BuildType.find(k)
    } unless params[:builds].nil?
    params[:tests].each { |k,v|
      @test_suite.test_types << TestType.find(k)
    } unless params[:tests].nil?
    if @test_suite.save
      flash[:notice] = "Suite #{@test_suite.name} created successfully."
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @test_suite = TestSuite.find(params[:id])
    @build_types = BuildType.find_all
    @test_types = TestType.find_all
    @title1 = 'Test suites'
    @url1 = '/test_suites/'
    @title2 = "Edit #{@test_suite.name}"
    @url2 = "/test_suites/edit/#{params[:id]}"
  end

  def update
    @test_suite = TestSuite.find(params[:id])
    
    @test_suite.build_types.clear
    @test_suite.test_types.clear
#     ActiveRecord::Base.connection.execute("DELETE FROM build_types_test_suites WHERE test_suite_id=#{@test_suite.id}")
#     ActiveRecord::Base.connection.execute("DELETE FROM test_suites_test_types WHERE test_suite_id=#{@test_suite.id}")
#     puts "DELETE FROM test_suites_test_types WHERE test_suite_id=#{@test_suite.id}"

    params[:builds].each { |k,v|
      @test_suite.build_types << BuildType.find(k)
    } unless params[:builds].nil?
    params[:tests].each { |k,v|
      @test_suite.test_types << TestType.find(k)
    } unless params[:tests].nil?
    
    
    
    if @test_suite.update_attributes(params[:test_suite])
      flash[:notice] = 'TestSuite was successfully updated.'
      redirect_to :action => 'show', :id => @test_suite
    else
      render :action => 'edit'
    end
  end

  def destroy
    TestSuite.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
